<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="配置名称或描述" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="配置类型" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="$router.go(-1)">
        返回
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="模板名称" width="250" align="center">
        <template slot-scope="{row}">
          <span>{{ row.ConfigTemplateName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="配置名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.Name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="配置值" align="center">
        <template slot-scope="{row}">
          <span>{{ row.Value }}</span>
        </template>
      </el-table-column>
      <el-table-column label="配置类型" align="center">
        <template slot-scope="{row}">
          <span>{{ row.TypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center">
        <template slot-scope="{row}">
          <span>{{ row.Description }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" style="margin-right: 10px;" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-popconfirm
            confirmButtonText="确定删除"
            cancelButtonText="取消"
            icon="el-icon-info"
            iconColor="red"
            title="确定要删除这条数据吗？"
            @onConfirm="handleDelete(row,$index)"
          >
            <el-button slot="reference" size="mini" type="danger">删除</el-button>
          </el-popconfirm>
          <el-button type="primary" size="mini" style="margin-left: 10px;" @click="handleSync(row)">
            同步
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageCode" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width: 400px; margin-left:50px;">
        <el-form-item label="配置名称" prop="Name">
          <el-input v-model="temp.Name" placeholder="请填写配置名称" />
        </el-form-item>

        <el-form-item label="配置参数" prop="Value">
          <el-input v-model="temp.Value" placeholder="请填写配置参数" />
        </el-form-item>

        <el-form-item label="配置类型" prop="Type">
          <el-select v-model="temp.Type" class="filter-item" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="详细描述" prop="Description">
          <el-input v-model="temp.Description" placeholder="请填写详细描述" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import * as homeHttp from '@/api/home'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageCode: 1,
        pageSize: 10,
        // importance: undefined,
        name: undefined,
        type: undefined
      },
      showReviewer: false,
      temp: {
        Name: undefined,
        Id: undefined,
        Value: undefined,
        Type: undefined,
        Description: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改模板',
        create: '添加模板'
      },
      dialogDetailVisible: false,
      detailData: {},
      rules: {
        Name: [{ required: true, message: '请填写配置名称', trigger: 'blur' }],
        Value: [{ required: true, message: '请填写配置参数', trigger: 'blur' }],
        Type: [{ required: true, message: '请选择配置类型', trigger: 'change' }],
        Description: [{ required: true, message: '请填写详细描述', trigger: 'blur' }]
      },
      downloadLoading: false,
      options: [
        { value: 1, label: '软件配置' },
        { value: 2, label: '硬件配置' }
      ],
      templateId: undefined,
      templatePrototypeId: undefined
    }
  },
  created() {
    this.templateId = this.$route.query.Id
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      const res = await homeHttp.getConfigTemplatePrototype({
        ...this.listQuery,
        templateId: this.templateId,
        pageCode: this.listQuery.pageCode - 1
      })

      if (res.Result) {
        this.list = res.Data
        this.total = res.Total
      }

      this.listLoading = false
    },
    handleFilter() {
      this.listQuery.pageCode = 1
      this.getList()
    },

    resetTemp() {
      this.temp = {
        id: undefined,
        name: undefined,
        Description: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          homeHttp.addConfigTemplatePrototype({
            ...this.temp,
            TemplateId: this.templateId
          }).then((data) => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: data.Msg || '新增成功',
              type: 'success',
              duration: 2000
            })

            this.syncConfirm(data.E)
          })
        }
      })
    },
    async handleUpdate(row) {
      const res = await homeHttp.getConfigTemplatePrototypeInfo({ id: row.Id })
      if (res.Result) {
        this.templatePrototypeId = res.Data.Id

        this.temp = Object.assign({}, row, res.Data) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp, { Id: this.templatePrototypeId })
          homeHttp.editConfigTemplatePrototype(tempData).then((res) => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: res.Msg || '更新成功',
              type: 'success',
              duration: 2000
            })

            this.syncConfirm(this.temp.Id)
          })
        }
      })
    },
    async handleDelete(row, index) {
      this.listLoading = true
      const res = await homeHttp.delConfigTemplatePrototype({ Id: row.Id })

      if (res.Result) {
        this.getList()
        this.$notify({
          title: '成功',
          message: res.Msg || '删除成功',
          type: 'success',
          duration: 2000
        })
        this.syncConfirm(row.Id)
      }
      this.listLoading = false
    },

    syncConfirm(Id) {
      this.$confirm('是否立即同步配置?', '同步', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        type: 'warning'
      }).then((res) => {
        this.$router.push({ path: '/Home/synchronization', query: { Id }})
      }).catch(() => {
        this.getList()
      })
    },

    handleSync(row) {
      this.$router.push({ path: '/Home/synchronization', query: { Id: row.Id }})
    }
  }
}
</script>
